package com.lindroy.androidplayer.ui.find.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import com.elvishew.xlog.XLog
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.databinding.FragmentNavigationIndexBinding
import com.lindroy.androidplayer.databinding.FragmentSquareBinding
import com.lindroy.androidplayer.logic.model.bean.NavigationIndexGroupItemBean
import com.lindroy.androidplayer.logic.model.bean.WebViewBean
import com.lindroy.androidplayer.logic.network.base.http.observeResponse
import com.lindroy.androidplayer.logic.network.base.http.observeState
import com.lindroy.androidplayer.ui.adapter.NavigationIndexPrimaryAdapterConfig
import com.lindroy.androidplayer.ui.adapter.NavigationIndexSecondaryAdapterConfig
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.viewmodels.NavigationViewModel
import com.lindroy.lib_utils.extensions.shortToast
import java.util.*

/**
 * @author Lin
 * @date 2022/1/23
 * @function 导航
 * @Description
 */
class NavigationIndexFragment : BaseLazyFragment<FragmentNavigationIndexBinding>() {

    private val viewModel by viewModels<NavigationViewModel>()

    private val navItemAdapter by lazy { NavigationIndexSecondaryAdapterConfig() }

    override fun FragmentNavigationIndexBinding.initView(savedInstanceState: Bundle?) {
        vm = viewModel
    }

    override fun FragmentNavigationIndexBinding.initListener() {
        viewModel.navigationLiveData.data.observeResponse(viewLifecycleOwner) { resp ->
            val navItems = arrayListOf<NavigationIndexGroupItemBean>()
            resp.forEach {
                navItems.add(NavigationIndexGroupItemBean(it.name))
                it.articles.forEach { article ->
                    navItems.add(
                        NavigationIndexGroupItemBean(
                            article.chapterName,
                            article.title,
                            article.link
                        )
                    )
                }
            }
            linkage.init(
                navItems,
                NavigationIndexPrimaryAdapterConfig(),
                navItemAdapter
            )
        }
        navItemAdapter.setOnItemClickListener {
            WebViewFragment.start(
                this@NavigationIndexFragment,
                url = it.link,
                title = it.itemName,
                collectedType = WebViewBean.TYPE_URL
            )
        }
    }

    override fun lazyLoad() {
        viewModel.navigationLiveData.load()
    }

    override fun onRetryClick(view: View) {
        super.onRetryClick(view)
        viewModel.navigationLiveData.retry()
    }

}